package com.atguigu.flink.timer;

import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2022/11/25
 *
 *  针对每种传感器输出最高的3个水位值
 */
public class Demo5_ListState
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
           .socketTextStream("hadoop103", 8888)
           .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
           .keyBy(WaterSensor::getId)
           .process(new KeyedProcessFunction<String, WaterSensor, String>()
           {



               @Override
               public void open(Configuration parameters) throws Exception {
                   listState = getRuntimeContext().getListState(new ListStateDescriptor<Integer>("top3", Integer.class));
               }
               //缓存目前的前三，和当前value的水位进行排序比较，之后获取新的前三，把前三存储起来
               private ListState<Integer> listState;

               @Override
               public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {

                   //把当前数据加入List
                   listState.add(value.getVc());

                   //排序取前3
                   List<Integer> top3List = StreamSupport.stream(listState.get().spliterator(), true)
                                                        //Comparator.reverseOrder(): 降序比较
                                                        .sorted(Comparator.reverseOrder())
                                                        .limit(3)
                                                        .collect(Collectors.toList());

                   //只需要保留前三
                   listState.update(top3List);

                   out.collect(ctx.getCurrentKey() + "："+top3List.toString());

               }
           })
           .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
